<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>购物车</title>
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <link rel="stylesheet" type="text/css" href="css/ziy.css">
    <link href="//unpkg.com/layui@2.9.14/dist/css/layui.css" rel="stylesheet">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
    <link rel="stylesheet" href="elementUI/elementCSS.css"/>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        .jinp_tuij_lb li {
            margin-right: 3%;
            width: 31%;
        }

        .jinp_tuij_lb li:nth-child(3n+3) {
            margin-right: 0;
        }

        .logo {
            width: 20% !important;
        }

        .search {
            width: 35% !important;
        }

        .search > input {
            width: 50% !important;
        }

        .myGomeWeb {
            display: flex;
            justify-content: center;
        }

        .myGomeWeb > div {
            float: none;
        }

        .myGomeWeb > div:first-of-type {
            margin-right: 30px;
        }

        [v-cloak] {
            display: none;
        }
    </style>
</head>
<body>
<div id="app" v-cloak>
    <nav class="navbar">
        <div class="nav-container" style="width: 100%; position: relative;">
            <a href="book.html" class="brand"><i class="bi bi-house-door"></i> 首页</a>
            <ul class="nav-links">
                <li><a href="dingdan.html"><i class="bi bi-clipboard-data"></i> 我的订单</a></li>
                <li><a href="gouwuche.html"><i class="bi bi-cart"></i> 我的购物车</a></li>
                <li><a href="myborrow.html"><i class="bi bi-journal-check"></i> 借书记录</a></li>
                <li><a href="#"><i class="bi bi-heart"></i> 我的收藏</a></li>
                <li><a href="gonggao.html"><i class="bi bi-megaphone"></i> 系统公告(5)</a></li>
                <li><a href="wenda.html"><i class="bi bi-chat-text"></i> 问答(5)</a></li>
                <li style="margin-left: 100px;">
                    <img @click="show_alter_info" style="width: 32px; cursor: pointer;" :src="user.profile"
                         alt="用户头像">
                </li>
                <li><a href="zhuye.html"><i class="bi bi-person"></i> 主页</a></li>
                <li @click="logout"><i class="bi bi-box-arrow-right"></i> 退出登录</li>
            </ul>
        </div>
    </nav>
    <!--头部end-->
    <div class="yiny yiny_gouwc">
        <div class="beij_center">
            <div class="cart-main-header clearfix">
                <div class="cart-col-1" style="width: 205px; height: 10px;"></div>
                <div class="cart-col-2"></div>
                <div class="cart-col-3">商品信息</div>
                <div class="cart-col-4">
                    <div class="cart-good-real-price">单价</div>
                </div>
                <div class="cart-col-5">数量</div>
                <div class="cart-col-6">
                    <div class="cart-good-amount">小计</div>
                </div>
                <div class="cart-col-7">操作</div>
            </div>
        </div>
        <!--商品信息-->
        <div class="container">
            <div class="cart-shop-goods dangq_honh" v-for="(item, index) in gouwuche_list" :key="item.id">
                <div class="cart-shop-good" style="display: flex;">
                    <div class="cart-col-1">
                        <input type="checkbox" class="jdcheckbox" v-model="item.selected"
                               @change="updateAllSelectStatus">
                    </div>
                    <div class="cart-col-2" style="height: 82px;">
                        <a :href="'xaingqing.html?id='+item.bookid" target="_blank" class="g-img">
                            <img :src="item.url" alt="商品图片">
                        </a>
                    </div>
                    <div class="fl houj_c">
                        <div class="cart-dfsg">
                            <div class="cart-good-name">
                                <a style="color: #101010;" :href="'xaingqing.html?id='+item.bookid"
                                   target="_blank">{{ item.bookname }}</a>
                            </div>
                        </div>
                        <div class="cart-good-pro"></div>
                        <div class="cart-col-4">
                            <div class="cart-good-real-price ">¥&nbsp;{{ item.price }}</div>
                        </div>
                        <div class="cart-col-5">
                            <div class="gui-count cart-count">
                                <a href="#" @click.prevent="updateQuantity(item, -1)"
                                   class="gui-count-btn gui-count-sub">-</a>
                                <div class="gui-count-input">
                                    <input class="" type="text" v-model.number="item.selectnum"
                                           @blur="updateItemTotal(item)">
                                </div>
                                <a href="#" @click.prevent="updateQuantity(item, 1)"
                                   class="gui-count-btn gui-count-add">+</a>
                            </div>

                            库存:{{ item.num }}}
                        </div>
                        <div class="cart-col-6 ">
                            <div class="cart-good-amount">¥&nbsp;{{ item.totalprice.toFixed(2) }}</div>
                        </div>
                    </div>
                    <div class="cart-col-7" style="margin-right: 46px;">
                        <div class="cart-good-fun delfixed">
                            <button style="padding: 1px 15px;" @click="del_gouwuche(item.id)" type="button"
                                    class="layui-btn layui-btn-xs layui-btn-danger layui-btn-normal">
                                <i class="layui-icon layui-icon-delete"></i> 删除
                            </button>
                        </div>
                        <div class="cart-good-fun">
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-warm layui-btn-normal">
                                移入收藏夹
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="jies_beij">
                <div class="beij_center over_dis">
                    <div class="cart-col-1 cart_jies">
                        <input type="checkbox" class="jdcheckbox" v-model="is_all_select" @change="selectAll">
                    </div>
                    <div class="qianm_shanc_yvf">
                        <span>全选</span>
                        <a href="#" @click="deleteSelected">删除</a>
                    </div>
                    <div class="jies_ann_bei">
                        <p>已选 <em>{{ selectedCount }}</em> 件商品 总计（不含运费）：<span>￥{{ selectedTotal.toFixed(2)
                            }}</span></p>
                        <a href="#" @click="processOrder" class="order_btn">去结算</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 引入 Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 引入 Axios 库 -->
<script src="js/axios.min.js"></script>
<script src="elementUI/elementJS.js"></script>
<!-- 引入 jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap JS 和依赖 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<!-- 引入 layui.js -->
<script src="layui/layui.js"></script>
<script src="js/data.js"></script>
<script src="js/pulblicfuntion.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            user: {},
            gouwuche_list: [],
            is_all_select: false,
            selectedCount: 0,
            selectedTotal: 0
        },
        created() {
            console.log("vue实例创建成功");
            // 读取登录用户信息
            axios.get(urlluodeng + '/user/getLoginUser').then((response) => {
                if (!response.data.result) {
                    alert(response.data.msg);
                    window.location.href = 'login.html';
                } else {
                    this.user = response.data.userData;
                    //获取购物车列表
                    axios.get(urlluodeng + '/gouwuche/getGouwucheList').then((response) => {
                        if (response.data.result) {
                            this.gouwuche_list = response.data.data;
                            //添加默认不选中
                            this.gouwuche_list.forEach(item => {
                                item.selected = false;
                                this.updateItemTotal(item); // 计算初始总价
                            });
                            console.log("购物车列表获取成功：");
                            console.log(this.gouwuche_list);


                            // 获取购物车里图书的限制数量
                        } else {
                            layer.msg("code:500", {icon: 2, time: 2000});
                        }
                    }).catch((error) => {
                        layer.msg("网络错误，请稍后再试", {icon: 2, time: 2000});
                    });
                }
            }).catch((error) => {
                console.log(error);
                layer.msg("用户信息获取失败，请重新登录", {icon: 2, time: 2000});
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1000);
            });
        },
        methods: {
            del_gouwuche(gouwuche_id) {
                console.log("删除购物车");
                console.log(gouwuche_id);

                layer.confirm('确认从购物车中删除该商品？', {
                    btn: ['确定', '取消'] // 按钮
                }, () => {
                    //确认删除
                    let delet_form = new FormData();
                    //键名要和后台接收的键名一致。gouwuche对象来接受数据
                    delet_form.append('id', gouwuche_id);
                    delet_form.append('user', this.user.username);
                    axios.post(urlluodeng + '/gouwuche/deleteGouwuche', delet_form).then((response) => {
                        if (response.data.result) {
                            layer.msg("删除成功", {icon: 1, time: 1000});
                            this.gouwuche_list.splice(this.gouwuche_list.findIndex(item => item.id === gouwuche_id), 1);
                            this.updateAllSelectStatus();
                        } else {
                            layer.msg("删除失败，失败代码:" + response.data.resultcode, {icon: 2, time: 2000});
                        }
                    }).catch((error) => {
                        layer.msg("网络错误，请稍后再试", {icon: 2, time: 2000});
                    });
                }, () => {
                    layer.msg("已取消", {icon: 1, time: 1000});
                });
            },
            show_alter_info() {
                showUserAvatar(this.user);
            },
            logout() {
                logout();
            },
            // 更新全选状态
            updateAllSelectStatus() {
                this.is_all_select = this.gouwuche_list.every(item => item.selected);
                this.computeTotal();
            },
            // 全选/取消全选
            selectAll() {
                this.gouwuche_list.forEach(item => {
                    item.selected = this.is_all_select;
                });
                this.computeTotal();
            },
            // 更新商品数量并计算小计
            updateQuantity(item, amount) {
                if (item.selectnum + amount > item.num) {
                    layer.msg("库存不足，请重新选择数量", {icon: 2, time: 2000});
                    return;
                }else if(item.selectnum + amount < 1){
                    layer.msg("数量不能低于1", {icon: 2, time: 2000});
                    return;
                }
                item.selectnum += amount;
                if (item.selectnum < 1) item.selectnum = 1; // 确保数量不低于1
                this.updateItemTotal(item);
            },
            // 更新单个商品的总价
            updateItemTotal(item) {
                console.log(item);
                // 获取当前商品的库存:
                let num = this.gouwuche_list.find(book => book.bookid === item.bookid);
                console.log("图书本身数据：");
                console.log(num);
                /* if ()*/


                item.totalprice = item.price * item.selectnum;
                this.computeTotal();
            },
            // 删除选中的商品
            deleteSelected() {
                const selectedItems = this.gouwuche_list.filter(item => item.selected);
                console.log("将要删除的商品：", selectedItems);

                // 如果实际需要删除，可以在这里调用接口进行删除操作
                this.gouwuche_list = this.gouwuche_list.filter(item => !item.selected);
                this.updateAllSelectStatus(); // 更新全选状态
            },
            // 处理结算
            processOrder() {
                const selectedItems = this.gouwuche_list.filter(item => item.selected);
                console.log("选中的商品：", selectedItems);
                // 在这里，你可以提交选中的商品信息到服务器进行结算
            },
            // 计算选中商品的总数量和总价
            computeTotal() {
                let totalQuantity = 0;
                let totalPrice = 0;

                this.gouwuche_list.forEach(item => {
                    if (item.selected) {
                        totalQuantity += item.selectnum;
                        totalPrice += item.totalprice;
                    }
                });

                this.selectedCount = totalQuantity;
                this.selectedTotal = totalPrice;
            }
        }
    });
</script>
</body>
</html>
